﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace Brunch.Forms
{
	public partial class BreadCrumbControl : UserControl
	{
		private const string delim = " | ";

		public BreadCrumbControl()
		{
			InitializeComponent();
			linkLabel.Text = string.Empty;
			((IButtonControl)linkLabel).DialogResult = DialogResult.None;
			crumb = string.Empty;
		}

		#region Properties

		public string Title
		{
			get { return lblTitle.Text; }
			set { lblTitle.Text = value; }
		}

		private string path;
		public string Path
		{
			get { return path; }
			set
			{
				if (path != value)
				{
					path = value;
					ProcessPath(path);
				}
			}
		}

		private string crumb;
		public string SelectedCrumb
		{
			get { return crumb; }
			set { crumb = value; }
		}

		#endregion

		#region Events

		public EventHandler<EventArgs<string>> breadcrumbSelected;
		public event EventHandler<EventArgs<string>> BreadcrumbSelected
		{
			add { breadcrumbSelected += value; }
			remove { breadcrumbSelected -= value; }
		}

		#endregion

		#region Methods

		/// <summary>
		/// Breaks a path into pieces, by folder and displays it as a breadcrumb trail.
		/// Uses a link label and the Visited property to denote selected directory.
		/// </summary>
		/// <param name="path"></param>
		private void ProcessPath(string path)
		{
			if (string.IsNullOrEmpty(path))
				return;

			LinkLabel.Link lnk = null;
			int start = 0, length;

			string[] parts = path.Split(System.IO.Path.DirectorySeparatorChar);

			foreach (string part in parts)
			{
				//don't display drive name
				if (part.EndsWith(System.IO.Path.VolumeSeparatorChar.ToString())) continue;

				//add "Directory |" to label, but link just "Directory"
				//string breadCrumb = 
				length = part.Length;
				linkLabel.Text += part + delim;
				lnk = linkLabel.Links.Add(start, length, part);

				//highlight current selected part
				if (!string.IsNullOrEmpty(crumb) && crumb == part)
					lnk.Visited = true;
				start += length + delim.Length;
			}
			//mark last link as visited
			if (lnk != null)
				lnk.Visited = true;

			linkLabel.Text = linkLabel.Text.Substring(0, linkLabel.Text.Length - delim.Length);
		}

		private void linkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			crumb = e.Link.LinkData as string;
			foreach (LinkLabel.Link lnk in linkLabel.Links)
				lnk.Visited = false;

			e.Link.Visited = true;
			if (breadcrumbSelected != null)
				breadcrumbSelected(this, new EventArgs<string>(crumb));
		}

		#endregion
	}
}
